<template>
  <div class="admin-page">
    <el-card class="admin-card">
      <template #header>
        <page-header title="用户管理">
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="warning" :disabled="!selectedRows.length" @click="handleBatchStatus(2)">批量禁用</el-button>
          <el-button type="success" :disabled="!selectedRows.length" @click="handleBatchStatus(1)">批量启用</el-button>
        </page-header>
      </template>

      <div class="admin-page-content">
        <div class="main-content">
          <div class="left-tree">
            <el-card class="tree-card" shadow="never">
              <template #header>
                <div class="tree-header">
                  <span>部门列表</span>
                </div>
              </template>
              <el-tree
                ref="deptTreeRef"
                :data="deptTreeData"
                :props="{ label: 'name' }"
                node-key="id"
                highlight-current
                @node-click="handleDeptSelect"
              />
            </el-card>
          </div>

          <div class="right-content">
            <div class="filter-container">
              <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="关键词">
                  <el-input
                    v-model="searchForm.keyword"
                    placeholder="用户名/姓名/手机/邮箱"
                    clearable
                    @keyup.enter="handleSearch"
                  />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                    <el-option label="待激活" value="0" />
                    <el-option label="正常" value="1" />
                    <el-option label="禁用" value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="部门">
                  <department-tree-select v-model="searchForm.departmentId" @select="handleDeptSelect" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="table-container">
              <el-table
                ref="tableRef"
                v-loading="loading"
                :data="userList"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="username" label="用户名" min-width="120" align="center" />
                <el-table-column prop="name" label="姓名" min-width="100" align="center" />
                <el-table-column prop="departments" label="所属部门" min-width="150" align="center">
                  <template #default="{ row }">
                    <div class="department-tags">
                      <el-tag 
                        v-for="dept in row.departments" 
                        :key="dept.id"
                        size="small"
                        class="mr-1"
                      >
                        {{ dept.name }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" min-width="120" align="center" />
                <el-table-column prop="email" label="邮箱" min-width="150" align="center" />
                <el-table-column prop="status" label="状态" width="100" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : row.status === 0 ? 'warning' : 'danger'">
                      {{ row.status === 1 ? '正常' : row.status === 0 ? '待激活' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="400" align="center">
                  <template #default="{ row }">
                    <div class="action-buttons">
                      <div class="primary-actions">
                        <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="success" size="small" @click="handleSetRole(row)">设置角色</el-button>
                        <el-button type="warning" size="small" @click="handleSetPermissions(row)">权限</el-button>
                      </div>
                      <div class="secondary-actions">
                        <el-button 
                          :type="row.status === 1 ? 'danger' : 'success'" 
                          size="small" 
                          @click="handleToggleStatus(row)"
                        >
                          {{ row.status === 1 ? '禁用' : '启用' }}
                        </el-button>
                        <el-button type="info" size="small" @click="handleResetPassword(row)">重置密码</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <div class="pagination-container">
          <base-pagination
            v-model:current-page="page"
            :total="total"
            :page-size="limit"
            @update:current-page="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 用户表单抽屉 -->
    <user-form-drawer
      v-model="drawerVisible"
      :edit-data="editData"
      @success="handleDrawerSuccess"
    />

    <!-- 角色设置对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="设置用户角色"
      width="500px"
      destroy-on-close
    >
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="角色">
          <el-select v-model="roleForm.roleId" placeholder="请选择角色">
            <el-option label="超级管理员" value="super_admin" />
            <el-option label="部门管理员" value="dept_admin" />
            <el-option label="普通用户" value="normal_user" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="roleForm.roleId === 'dept_admin'" label="主部门">
          <department-tree-select 
            v-model="roleForm.primaryDepartmentId"
            placeholder="请选择主部门"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="设置用户权限"
      width="600px"
      destroy-on-close
    >
      <permission-rule-editor
        v-model="permissionForm.permissions"
        :template-type="'custom'"
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageHeader from '@/components/PageHeader.vue'
import BasePagination from '@/components/BasePagination.vue'
import UserFormDrawer from '@/components/UserFormDrawer.vue'
import DepartmentTreeSelect from '@/components/DepartmentTreeSelect.vue'
import PermissionRuleEditor from '@/components/PermissionRuleEditor.vue'
import { userApi } from '@/api/userApi'
import { departmentApi } from '@/api/departmentApi'

// 部门树数据
const deptTreeData = ref([])
const deptTreeRef = ref(null)

// 表格数据
const loading = ref(false)
const userList = ref([])
const tableRef = ref(null)

// 分页参数
const page = ref(1)
const limit = ref(20)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  departmentId: ''
})

// 抽屉相关
const drawerVisible = ref(false)
const editData = ref(null)

// 批量操作相关
const selectedRows = ref([])

// 角色对话框
const roleDialogVisible = ref(false)
const roleForm = reactive({
  userId: null,
  roleId: '',
  primaryDepartmentId: ''
})

// 权限对话框
const permissionDialogVisible = ref(false)
const permissionForm = reactive({
  userId: null,
  permissions: {
    system: [],
    business: [],
    data: {
      scope: 'self',
      fields: []
    }
  }
})

// 获取部门树数据
const loadDeptTree = async () => {
  try {
    const res = await departmentApi.getDepartmentTree()
    if (res.code === 200) {
      deptTreeData.value = res.data
    } else {
      ElMessage.error(res.message || '获取部门树失败')
    }
  } catch (error) {
    console.error('获取部门树失败:', error)
    ElMessage.error('获取部门树失败')
  }
}

// 获取用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const res = await userApi.getUsers({
      page: page.value,
      limit: limit.value,
      keyword: searchForm.keyword,
      status: searchForm.status,
      departmentId: searchForm.departmentId
    })
    
    if (res.code === 200) {
      userList.value = res.data.items
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 部门选择
const handleDeptSelect = (data) => {
  searchForm.departmentId = data.id
  handleSearch()
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadUserList()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.departmentId = ''
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  editData.value = null
  drawerVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  editData.value = row
  drawerVisible.value = true
}

// 抽屉提交成功
const handleDrawerSuccess = () => {
  loadUserList()
}

// 更改用户状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1
    const res = await userApi.updateUserStatus(row.id, newStatus)
    
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
      loadUserList()
    } else {
      ElMessage.error(res.message || '状态更新失败')
    }
  } catch (error) {
    console.error('更新用户状态失败:', error)
    ElMessage.error('更新用户状态失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await userApi.deleteUser(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadUserList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 页码改变
const handleCurrentChange = (val) => {
  page.value = val
  loadUserList()
}

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    const res = await userApi.batchDeleteUsers(selectedRows.value.map(row => row.id))
    if (res.code === 200) {
      ElMessage.success('批量删除成功')
      loadUserList()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 批量更改状态
const handleBatchStatus = async (newStatus) => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要更改状态的用户')
    return
  }

  try {
    const res = await userApi.batchUpdateUsersStatus(selectedRows.value.map(row => row.id), newStatus)
    if (res.code === 200) {
      ElMessage.success('批量状态更新成功')
      loadUserList()
    } else {
      ElMessage.error(res.message || '批量状态更新失败')
    }
  } catch (error) {
    console.error('批量状态更新失败:', error)
    ElMessage.error('批量状态更新失败')
  }
}

// 重置用户密码
const handleResetPassword = (row) => {
  ElMessageBox.confirm(
    '确定要重置该用户的密码吗？重置后密码将变为：123456',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await userApi.resetUserPassword(row.id)
      if (res.code === 200) {
        ElMessage.success('密码重置成功')
      } else {
        ElMessage.error(res.message || '密码重置失败')
      }
    } catch (error) {
      console.error('重置用户密码失败:', error)
      ElMessage.error('密码重置失败')
    }
  }).catch(() => {})
}

// 设置角色
const handleSetRole = (row) => {
  roleForm.userId = row.id
  roleForm.roleId = row.role_id || 'normal_user'
  roleForm.primaryDepartmentId = row.primary_department_id || ''
  roleDialogVisible.value = true
}

// 提交角色设置
const handleRoleSubmit = async () => {
  try {
    if (roleForm.roleId === 'dept_admin' && !roleForm.primaryDepartmentId) {
      return ElMessage.warning('请选择主部门')
    }

    const res = await userApi.updateUser(roleForm.userId, {
      role_id: roleForm.roleId,
      primary_department_id: roleForm.roleId === 'dept_admin' ? roleForm.primaryDepartmentId : null
    })

    if (res.code === 200) {
      ElMessage.success('角色设置成功')
      roleDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(res.message || '设置角色失败')
    }
  } catch (error) {
    console.error('设置角色失败:', error)
    ElMessage.error('设置角色失败')
  }
}

// 设置权限
const handleSetPermissions = (row) => {
  permissionForm.userId = row.id
  // TODO: 加载用户当前权限
  permissionDialogVisible.value = true
}

// 提交权限设置
const handlePermissionSubmit = async () => {
  try {
    const res = await userApi.setUserPermissions(
      permissionForm.userId,
      permissionForm.permissions
    )

    if (res.code === 200) {
      ElMessage.success('权限设置成功')
      permissionDialogVisible.value = false
    }
  } catch (error) {
    console.error('设置权限失败:', error)
    ElMessage.error('设置权限失败')
  }
}

onMounted(() => {
  loadDeptTree()
  loadUserList()
})
</script>

<style lang="scss" scoped>
.admin-page {
  height: 100%;
  
  .admin-card {
    height: 100%;
    
    :deep(.el-card__body) {
      height: calc(100% - 56px);
      padding: 16px;
      display: flex;
      flex-direction: column;
    }
  }
}

.admin-page-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
}

.left-tree {
  width: 250px;
  
  .tree-card {
    height: 100%;
  }
}

.right-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 16px;
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
}

.table-container {
  flex: 1;
  overflow: auto;
  
  :deep(.el-table) {
    height: 100%;
  }
}

.pagination-container {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e6e6e6;
  text-align: right;
}

.department-tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 4px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;

  .primary-actions,
  .secondary-actions {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
}
</style> 